package com.nb.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.nb.DTO.*;
import com.nb.entity.*;
import com.nb.mapper.*;
import com.nb.service.LawyerManagerService;
import jakarta.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LawyerManagerServiceImpl implements LawyerManagerService {

    @Autowired
    private LawyerMapper lawyerMapper;


    @Resource
    private CaseMapper caseMapper;

    @Resource
    private CaseLawyerMapper caseLawyerMapper;


    @Override
    public LawyerInfoDTO getLawyerInfo(Long lawyerId) {
        Lawyer lawyer = lawyerMapper.selectOneById(lawyerId);
        if (lawyer == null) {
            throw new RuntimeException("律师不存在");
        }
        // 实体转DTO
        LawyerInfoDTO dto = new LawyerInfoDTO();
        dto.setId(lawyer.getId());
        dto.setLicenseNo(lawyer.getLicenseNo());
        dto.setSpecialty(lawyer.getSpecialty());
        dto.setYearsOfPractice(lawyer.getYearsOfPractice());
        dto.setIntroduction(lawyer.getIntroduction());
        dto.setServiceArea(lawyer.getServiceArea());
        dto.setSuccessRate(lawyer.getSuccessRate());
        return dto;
    }

    @Override
    @Transactional
    public void updateLawyerInfo(LawyerInfoDTO infoDTO) {
        Lawyer lawyer = lawyerMapper.selectOneById(infoDTO.getId());
        if (lawyer == null) {
            throw new RuntimeException("律师不存在");
        }
        // 更新字段
        lawyer.setLicenseNo(infoDTO.getLicenseNo());
        lawyer.setSpecialty(infoDTO.getSpecialty());
        lawyer.setYearsOfPractice(infoDTO.getYearsOfPractice());
        lawyer.setIntroduction(infoDTO.getIntroduction());
        lawyer.setServiceArea(infoDTO.getServiceArea());
        lawyer.setSuccessRate(infoDTO.getSuccessRate());
        lawyer.setUpdateTime(LocalDateTime.now());
        lawyerMapper.update(lawyer);
    }

    @Override
    public LawyerPerformanceDTO getLawyerPerformance(Long lawyerId) {
        // 1. 查询接案总量
        QueryWrapper caseQuery = new QueryWrapper();
        caseQuery.eq("id", lawyerId);
        long caseCount = lawyerMapper.selectCountByQuery(caseQuery);

        // 2. 计算平均响应时间（assign_time到accept_time的差值）
        List<CaseLawyer> caseLawyers = caseLawyerMapper.selectAll()
                .stream()
                .filter(cl -> cl.getLawyerId().equals(lawyerId))
                .collect(Collectors.toList());
        double totalHours = 0;
        int validCount = 0;
        LocalDateTime firstCaseTime = null;
        LocalDateTime latestCaseTime = null;

        for (CaseLawyer cl : caseLawyers) {
            if (cl.getAcceptTime() != null) {
                Duration duration = Duration.between(cl.getAssignTime(), cl.getAcceptTime());
                totalHours += duration.toHours();
                validCount++;
            }
            // 记录首次和最近接案时间
            if (firstCaseTime == null || cl.getAssignTime().isBefore(firstCaseTime)) {
                firstCaseTime = cl.getAssignTime();
            }
            if (latestCaseTime == null || cl.getAssignTime().isAfter(latestCaseTime)) {
                latestCaseTime = cl.getAssignTime();
            }
        }

        // 3. 组装结果
        Lawyer lawyer = lawyerMapper.selectOneById(lawyerId);
        LawyerPerformanceDTO dto = new LawyerPerformanceDTO();
        dto.setLawyerId(lawyerId);
        dto.setCaseCount((int) caseCount);
        dto.setSuccessRate(lawyer.getSuccessRate() != null ? BigDecimal.valueOf(lawyer.getSuccessRate()) : BigDecimal.ZERO);
        dto.setAvgResponseHours(validCount > 0 ? totalHours / validCount : 0D);
        dto.setFirstCaseTime(firstCaseTime);
        dto.setLatestCaseTime(latestCaseTime);
        return dto;
    }

    @Override
    public List<LawyerPerformanceDTO> listLawyerPerformance() {
        // 查询所有律师并批量计算绩效（实际场景建议分页）
        List<Lawyer> lawyers = lawyerMapper.selectAll();
        return lawyers.stream()
                .map(lawyer -> getLawyerPerformance(lawyer.getId()))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void assignCase(CaseAssignDTO assignDTO) {
        // 校验案件和律师是否存在
        Case legalCase = caseMapper.selectOneById(assignDTO.getCaseId());
        if (legalCase == null) {
            throw new RuntimeException("案件不存在");
        }
        if (lawyerMapper.selectOneById(assignDTO.getLawyerId()) == null) {
            throw new RuntimeException("律师不存在");
        }

        // 更新案件表的承办律师ID
        legalCase.setLawyerId(assignDTO.getLawyerId());
        legalCase.setAssignTime(LocalDateTime.now());
        legalCase.setStatus("ASSIGNED"); // 更新案件状态为已分配
        caseMapper.update(legalCase);

        // 记录案件-律师关联关系
        caseLawyerMapper.insert(new CaseLawyer()
                .setCaseId(assignDTO.getCaseId())
                .setLawyerId(assignDTO.getLawyerId())
                .setAssignTime(LocalDateTime.now()));
    }


    @Override
    public List<LawyerInfoDTO> searchLawyers(LawyerSearchDTO searchDTO) {
        QueryWrapper query = new QueryWrapper();
        // 构建查询条件
        if (searchDTO.getSpecialty() != null) {
            query.like("specialty", searchDTO.getSpecialty());
        }
        if (searchDTO.getServiceArea() != null) {
            query.like("service_area", searchDTO.getServiceArea());
        }
        if (searchDTO.getMinYears() != null) {
            query.ge("years_of_practice", searchDTO.getMinYears());
        }
        if (searchDTO.getMinSuccessRate() != null) {
            query.ge("success_rate", searchDTO.getMinSuccessRate());
        }

        // 查询并转换为DTO
        return lawyerMapper.selectAll()
                .stream()
                .map(lawyer -> {
                    LawyerInfoDTO dto = new LawyerInfoDTO();
                    dto.setId(lawyer.getId());
                    dto.setLicenseNo(lawyer.getLicenseNo());
                    dto.setSpecialty(lawyer.getSpecialty());
                    dto.setYearsOfPractice(lawyer.getYearsOfPractice());
                    dto.setServiceArea(lawyer.getServiceArea());
                    dto.setSuccessRate(lawyer.getSuccessRate());
                    return dto;
                })
                .collect(Collectors.toList());
    }


}